<template>
	<view class="flex justify-center" style="background-color: #F5F5F9;">
		<scroll-view :scroll-y="true" :style="{height:scrollHeight+'px'}">

			<view style="width: 100%;">
				<!-- 第一个 -->
				<view class="card padding margin-top-xs">
					<view class="text-xxxl">{{info.title}}</view>
					<view class="flex padding-top">任务分类：<view class="text-bold">{{info.type}}</view>
					</view>
					<view class="flex padding-top-xs"> 状态：<view style="color: #80c9f4;" class="text-bold">
							{{info.status}}
						</view>
					</view>
					<view class="flex align-end padding-top-xs">截止日期：<view class="text-bold">{{info.endTime}}</view>
					</view>
				</view>

				<view class="card padding">
					<view class="text-bold">描述</view>
					<view class="padding-top">
						<rich-text :nodes="info.description"></rich-text>
					</view>
				</view>
				<view class="card padding margin-top-sm">
					<view class="text-bold">提交照片</view>
					<u-form labelWidth="100" labelPosition="left" :model="form" ref="form">
						<u-form-item label="照片" style="height: 120%" prop="file">
							<u-upload :disabled="readOnly" :fileList="fileList1" @afterRead="afterRead"
								@delete="deletePic" name="1" multiple :maxCount="1"></u-upload>
						</u-form-item>
					</u-form>
				</view>
			</view>
		</scroll-view>



		<!-- 底部返回 -->
		<view class="bottom flex justify-center align-center">
			<view class="padding-right-xl">
				<view class="flex justify-center">
					<u-icon name="arrow-leftward" size="22" color="#a7b6b1"></u-icon>
				</view>
				<view style="color: #a7b6b1;" @click="toPage('/pages/work/task/index')">返回</view>
			</view>
			<view style="width: 500upx;">
				<u-button @click="confirm" type="primary" :disabled="submitDisabled" :text="submitBtnText" />
			</view>
		</view>
	</view>
</template>

<script>
	import {
		getDetail,
		update,
		uploadPhoto
	} from '@/api/task.js'
	import {
		getAccessToken
	} from "@/utils/auth";
	import {
		formatRichText
	} from '@/utils/common.js'
	import {
		baseUrl
	} from '@/config'
	export default {
		watch: {
			'info.partStatus': {
				handler(v) {
					if (v === '未完成') {
						this.submitBtnText = '提交'
						this.submitDisabled = false
					} else {
						this.submitBtnText = '已提交'
						this.submitDisabled = true
					}
				},
				deep: true
			}
		},
		onLoad(option) {
			this.id = option.id
			this.detail()
		},
		onReady() {
			let _this = this;
			uni.getSystemInfo({ //调用uni-app接口获取屏幕高度
				success(res) { //成功回调函数
					let wHeight = res.windowHeight //windoHeight为窗口高度，主要使用的是这个
					let bottomH = uni.createSelectorQuery().select(".bottom"); //想要获取高度的元素名（class/id）
					bottomH.boundingClientRect(data => {
						_this.scrollHeight = data.top //计算高度：元素高度=窗口高度-元素距离顶部的距离（data.top）
					}).exec()
				}
			})
		},
		data() {
			return {
				submitBtnText: '提交',
				submitDisabled: false,
				id: undefined,
				info: {},
				returnUrl: '/static/work/banner.jpg',
				toBeSignedUsers: [],
				imgUploadSuccess: false,
				queryParams: {
					pageNo: 1,
					pageSize: 5,
					docId: this.id
				},
				// 上传工单照片
				upload: {
					url: baseUrl + "/admin-api/infra/file/upload", // 请求地址
					headers: {
						'Authorization': "Bearer " + getAccessToken()
					}, // 设置上传的请求头部
					data: {} // 上传的额外数据，用于文件名
				},
				scrollHeight: undefined,
				fileList1: [],
				form: {},
				readOnly: false
			}
		},
		methods: {
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				console.log('event=====', event)
				if(event.file[0].size / 1024 / 1024 > 2){
					uni.$u.toast('图片不能大于2mb')
					return
				}
				
				this.submitBtnText = '上传中...'
				this.submitDisabled = true
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				console.log('lists=======', lists)
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					console.log('result=====', result)
					let item = this[`fileList${event.name}`][fileListLen]
					console.log('item=====', item)
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
				console.log('fileList=====', this.fileList1)
			},
			uploadFilePromise(url) {
				let _this = this
				let baseUrl = _this.upload.url
				return new Promise((resolve, reject) => {
					let data = {
						name: 'photo',
						filePath: url
					}
					uploadPhoto(data).then(res => {
						uni.showToast({
							title: "上传成功",
							icon: 'success'
						})
						_this.imgUploadSuccess = true,
						console.log('_this.imgUploadSuccess =====', _this.imgUploadSuccess)
						_this.submitBtnText = '提交'
						_this.submitDisabled = false
						resolve(res.data)
					})
				})
			},
			detail() {
				getDetail(this.id).then(res => {
					this.info = res.data
					this.info.description = formatRichText(this.info.description)
					this.info.partStatus === '已完成' ? this.readOnly = true : this.readOnly = false
					if (this.info.fileUrl) {
						this.info.fileUrl.split(',').forEach(url => {
							this.fileList1.push({
								url: url
							})
						})
					}
				})
			},
			toPage(toUrl) {
				uni.navigateTo({
					url: toUrl
				})
			},
			confirm() {
				const that = this
				if (this.fileList1.length === 0) {
					uni.$u.toast('请上传照片')
					return
				}
				that.info.fileUrl = that.fileList1[0].url
				if (that.imgUploadSuccess === false) {
					uni.showToast({
						title: '图片未上传完成，请等待...',
						duration: 2000
					});
					return
				}
				update(that.info.fileUrl, that.id).then(res => {
					uni.showToast({
						title: '提交完成',
						duration: 2000
					});
					that.fileList1 = []
					that.imgUploadSuccess = false
					this.detail()
				})

			}
		}
	}
</script>

<style scoped lang="less">
	.card {
		width: 100%;
		border-radius: 10upx;
		box-shadow: 1px 1px 1px 0 rgba(0, 0, 0, 0.1), -1px -1px 3px 0 rgba(0, 0, 0, 0.1);
		background-color: #ffffff;
	}

	.bottom {
		position: fixed;
		bottom: 0;
		box-shadow: 1px 1px 1px 0 rgba(0, 0, 0, 0.1), -1px -1px 3px 0 rgba(0, 0, 0, 0.1);
		width: 100%;
		height: 100upx;
	}
</style>